package com.tpl.core.basedata.action.sys;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.tpl.core.JsonUtil;
import com.tpl.core.action.BaseAction;
import com.tpl.core.basedata.common.constant.ICacheConstants;
import com.tpl.core.basedata.service.AuthService;
import com.tpl.core.basedata.service.RoleService;
import com.tpl.core.common.DateUtil;
import com.tpl.core.common.TreeHelper;
import com.tpl.core.common.ValidateUtil;
import com.tpl.core.common.exception.RuleException;
import com.tpl.core.common.page.Page;
import com.tpl.core.common.redis.RedisClientUtil;
import com.tpl.core.entity.SessionUser;
import com.tpl.core.entity.sys.Role;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 *
 *
 * 
 */
@Controller
@RequestMapping("/deptRole")
public class RoleAction extends BaseAction {
	
	
	private static final long serialVersionUID = 8227303179526564660L;

	@Autowired
	private RoleService roleService;
	@Autowired
	private AuthService authService;
	
	@RequestMapping("/toDeptRoleManage.do")
	public String toDeptRoleManage(){
		return "role/deptRoleManage";
	}
	@RequestMapping("/toDeptRole.do")
	public String toDeptRoleList(){
		
		return "role/deptRole_list";
	}
	/**
	 * 获取角色列表
	 * @param deptId 部门id
	 * */
	@RequestMapping("/getDeptRoleList.do")
	public String getDeptRoleList(Long deptId, Role role, HttpServletRequest request){
		Page page = roleService.getRolePage(deptId, getPageIndex(), getPageSize());
		putInRequest("page", page, "deptId",deptId,"role",role);
		return "role/role_list";
	}
	/**
	 * 跳转到新增页面
	 * @param deptId
	 * @return
	 */
	@RequestMapping("/toAddRole.do")
	public String toAddRole(Long deptId){
		putInRequest("deptId", deptId);
		return "system/deptRole_roleEdit";
	}
	
	/**
	 * 跳转到新增页面
	 * @return
	 */
	@RequestMapping("/toEditRole.do")
	public String toEditRole(Long roleId){
		//putInRequest("deptId", deptId);
		Role role = roleService.getRoleById(roleId);
		putInRequest("role", role,"deptId",role.getDeptId());
		return "system/deptRole_roleEdit";
	}
	
	/**
	 * 保存角色
	 */
	@RequestMapping("/saveRole.do")
	public @ResponseBody void toSaveRole(Role role){
		ValidateUtil.validLength(role.getRoleName(), 2, 10, "角色名称");
		role.setCreator(getLoginUser().getUserNo());
		role.setUpdator(getLoginUser().getUserNo());
		role.setCreateDate(DateUtil.now());
		role.setUpdateDate(DateUtil.now());
		if(role.getId() != null){
			roleService.update(role);
		}else{
			roleService.saveRole(role);
		}
		outJsonSuccess();
	}
	
	/**
	 * 跳转到部门对应的角色列表
	 * @param deptId
	 * @return
	 */
//	@RequestMapping("/toDeptRoleList.do")
//	public String toDeptRoleList(Long deptId){
//		if(deptId!=null){
//			List<Role> list = roleService.getRoles(deptId);
//			putInRequest("list",list);
//		}
//		putInRequest("deptId", deptId);
//		return "system/deptRole_role";
//	}
	
	/**
	 * ajax通过角色id获取对应的菜单
	 * @param roleId
	 */
	@RequestMapping("/getMenusByRoleId.do")
	public @ResponseBody void getMenusByRoleId(Long roleId){
		Role roleList = roleService.getRoleById(roleId);
		if(roleList.getQuoteRoleId()!=null)//判断是否引用，如果引用权限指向引用
		{
			roleId = roleList.getQuoteRoleId();
		}
		List<Role> list = roleService.getMenuByRoleId(roleId);
		JSONArray ja=JsonUtil.toJSONArray(list);
		outJsonSuccess(ja.toString());
	}
	
	
	/**
	 * 保存编辑的角色菜单内容
	 * @param del_
	 * @param new_
	 * @param roleId
	 */
	@RequestMapping("/saveRoleMenu.do")
	public @ResponseBody void saveRoleMenu(Long[] del_,Long[] new_,Long roleId){
		Role role = roleService.getRoleById(roleId);
		if(role.getQuoteRoleId()!=null)
		{
			throw new RuleException("参照基础角色不能修改权限");
		}
		roleService.saveRoleMenu(del_, new_, roleId);
		clearCache(roleId,null);
		outJsonSuccess();
	}
	
	/**
	 * 启用和禁用
	 * @param roleId
	 * @param state
	 */
	@RequestMapping("/updateState.do")
	public @ResponseBody void updateState(Long roleId, String state){
		List<Role> roles=roleService.getRoleUserByParam(null, roleId);
		roleService.updateState(roleId, state);
		clearCache(roleId,roles);
		outJsonSuccess();
	}
	
	/**
	 * 清空角色下人员
	 * @param roleId
	 */
	@RequestMapping("/empty.do")
	public @ResponseBody void empty(Long roleId){
		
			List<Role> roles=roleService.getRoleUserByParam(null, roleId);

		roleService.doClearRoleUser(roleId,null);
		
		clearCache(roleId,roles);
		outJsonSuccess();
	}
	
	/**
	 * 删除角色
	 * @param roleId
	 */
	@RequestMapping("/delRole.do")
	public @ResponseBody void delRole(Long roleId){
		Long num = roleService.getUserNumByRoleId(roleId, getLoginUser().getId());
		if(num>0){
			outJsonFailure("角色下存在人员，请先清空角色！");
		}else{
			roleService.delete(roleId);
			clearCache(roleId,null);
			outJsonSuccess("删除成功！");
		}
	}
	/**
	 * 清除缓存
	 */
	private void clearCache(Long roleId,List<Role> roles){
		if(roles!=null){
			Role role=roleService.getRoleById(roleId);
			for(Role r : roles)
				RedisClientUtil.delkeyObject(ICacheConstants.CACHE_AUTH_USER_ROLE+role.getDeptId()+"#"+r.getUserId());
		}
		RedisClientUtil.delkeyObject(ICacheConstants.CACHE_AUTH_ROLE_MENU+roleId);
		RedisClientUtil.delkeyObject(ICacheConstants.CACHE_AUTH_ROLE_MENU);
	}
	
	@RequestMapping("/getReferTree.do")
	public @ResponseBody void getReferTree(){
		SessionUser user=getLoginUser();
		JSONArray ja=authService.getUserDept(user); //获取当前用户下的所有部门 并返回json
		List list=new ArrayList();
		Long curDeptId=user.getDept().getId();//登录部门ID
		JSONObject curDept=new JSONObject();
		Long rootId=0L;
		String deptIds="";
		for(int i=0,len=ja.size();i<len;i++){   //遍历所有部门
			JSONObject jo=ja.getJSONObject(i);
			if(jo.containsKey("root")&&jo.getBoolean("root"))
				rootId=jo.getLong("parentId");
			jo.put("roleName", jo.get("deptName"));
			jo.put("deptFlag", "1");
			list.add(jo);
			deptIds+=jo.getLong("id")+",";
		}
		if(deptIds.length()>0) deptIds=deptIds.substring(0, deptIds.length()-1);
		List roles=roleService.getRolesByMoreDeptId(deptIds);
		JSONArray rls=JsonUtil.toJSONArray(roles);
		for(int i=0,count=rls.size();i<count;i++){
			JSONObject rl=rls.getJSONObject(i);
			rl.put("id","r_"+rl.get("id"));
			rl.put("parentId", rl.get("deptId"));
			//rl.put("deptName", rl.get("roleName"));
			list.add(0,rl);
		}
		final Long root=rootId;
		TreeHelper tree=new TreeHelper(new String[]{"id","roleName","parentId","deptFlag","baseRole"},list,2) {
			@Override
			public Object root() {
				return root;
			}
			@Override
			public Object[] idTextData(Object[] nodeData) {
				Object text=nodeData[1];
				if(nodeData[3]!=null&&Long.valueOf(nodeData[3].toString())>0)
					text=nodeData[1]+"(部门)";
				else if(nodeData[4].equals(true))
					text=nodeData[1]+"(基础角色)";
				else
					text=nodeData[1]+"(角色)";
				return new Object[]{nodeData[0],text};
			}
			@Override
			protected void setJsonAttributesData(JSONObject jo, String[] keys, Object[] nodeData) {
				super.setJsonAttributesData(jo, keys, nodeData);
				if(jo.containsKey("deptFlag")&&jo.getString("deptFlag").equals("1")){
					jo.put("nocheck", true);
				}
			}
		};
		//putInRequest("depts", ja.toString(),"treeData",tree.toString(),"curDept",curDept);
		//return "system/deptRole_refer";
		outJson(tree);
	}
	
	@RequestMapping("/referRoles.do")
	public @ResponseBody void referRoles(Long deptId,String [] roles){
		List<Role> list =JsonUtil.toJSONArray(roles).toJavaList(Role.class);
		roleService.doReferRoles(deptId, list,getLoginUser().getUserNo());
		outJsonSuccess("角色参照成功！");
	}
	

}
